import requests

#cookie导入，兼容py2,py3

try:
	import cookielib
except:
	import http.cookiejar as cookielib

import re

agent="Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/71.0.3578.98 Safari/537.36"
headers={
	"User-Agent":agent,
	"referer":"https://ruby-china.org/account/sign_in",
	"x-csrf-token":"A4pJgSK++VP+nB5276UaZlqk9dGyyoqvs2yeZrPWM5jCCBAXSMWfG339IAdGX4/hSEFEa1q254CWvscapml+4w=="
}

session=requests.session()
session.cookies=cookielib.LWPCookieJar(filename="ruby_china_cookies.txt")

#加载cookie
try:
	session.cookies.load(ignore_discard=True)
	print("cookie加载成功")
except:
	print("cookie加载失败")


def get_index():
	response=session.get("http://www.ixuea.com/orders",headers=headers)
	with open("ixuea_index.html","wb") as f:
		f.write(response.text.encode("utf8"))

	print("ok")



def get_xsrf():
	# response=requests.get("https://www.zhihu.com/",headers=headers)
	# print(response.text)

	# #这里匹配我们官网
	# text='<meta name="csrf-token" content="3KFqJDWakeTl8VMeXQShnRHz5Iymm78TpchVGjdN6/GRP/34WW313xT0r4R+Z0GL0tbRxTjlPKZvKZW5B6c1EQ==" />'
	# match_result=re.match('.*meta name="csrf-token" content="(.*?)" />',text)
	# if match_result:
	# 	print(match_result.group(1))
	# return ""

	# ruby china
	response=requests.get("https://ruby-china.org/account/sign_in",headers=headers)
	# response=requests.get("http://www.ixuea.com/",headers=headers)
	# print(response.text)

	text = response.text
	#DOTALL：匹配所有文章，默认只匹配一行
	match_result = re.match('.*meta name="csrf-token" content="(.*?)" />', text,re.DOTALL)
	if match_result:
		print(match_result.group(1))
	return ""

def get_capt():
	url="https://timgsa.baidu.com/timg?image&quality=80&size=b9999_10000&sec=1547455970626&di=81c90b6c569594978acb0b988e8c1535&imgtype=0&src=http%3A%2F%2Fwww.xiaobaixitong.com%2Fd%2Ffile%2Fhelp%2F2018-08-06%2Ff15ce5d652d8da38e9e0e384f35b39d7.png"
	response=session.get(url)
	with open("capt.jpg","wb") as f:
		f.write(response.content)

	from PIL import Image
	try:
		im=Image.open("capt.jpg")
		im.show()
		im.close()
	except:
		pass

	#让用户从控制台输入
	capt=input("输入验证码\n")

	#python2
	# raw_input

	return capt

def login(username,password):
	#知乎登录

	#判断是手机号函数邮箱
	# if re.match("^1\d{10}",username):
	print("手机号登录")

	#获取验证码，用户输入的
	cap=get_capt()

	post_url="https://ruby-china.org/account/sign_in"
	post_data={
		"user[login]":username,
		"user[password]":password,
		"user[remember_me]":"1",
		"cap":cap
	}

	response_text=session.post(post_url,data=post_data,headers=headers)
	print(response_text.text)

	session.cookies.save()

login("lifengsoft","RPQ13698275312n")

# get_index()

# get_xsrf()